/**@file
   Logger class header file.
   
   @par license 
   Copyright 2012 Lu, Ken. All rights reserved.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 
   @author: Lu, Ken (bluewish.ken.lu@gmail.com)
**/

#include <assert.h>
#include <string>
#include <Windows.h>
#include <fstream>

#include "logger.h"

using namespace std;

namespace ken {

int32_t Logger::level_ = Logger::LOG_DEBUG;
bool Logger::is_show_detail_  = false;

Logger::Logger(void)
{
}


Logger::~Logger(void)
{
}

void Logger::LogMessage(LEVEL level, const char* function, int line, const char* file, bool noprefix, const char* format, ...)
{
    va_list marker;
    char message[1024] = {0};

    if (level < Logger::level_) {
        return;
    }

    if (is_show_detail_) {
        sprintf_s(message, "%s (%003d)\n", file, line);
        ::OutputDebugStringA(message);
    }

    std::string prefix = "";
    switch (level) {
    case LOG_DEBUG:
        prefix = "D ";
        break;
    case LOG_INFO:
        prefix = "I ";
        break;
    case LOG_WARNING:
        prefix = "W ";
        break;
    case LOG_ERROR:
        prefix = "E ";
        break;
    case LOG_CRITICAL:
        prefix = "C ";
        break;
    default:
        prefix = "? ";
    }
    
    prefix += "[";
    prefix += function;
    prefix += "] ";

    memset(message, 0, 1024);
    va_start(marker, format);
    _vsnprintf_s(message, 1024, format, marker);
    va_end(marker);

    std::string statement;
    if (noprefix) {
        statement = message;
    } else {
        statement = prefix + message;
    }
    statement += "\n";
    ::OutputDebugStringA(statement.c_str());
    printf(statement.c_str());

    ofstream dumpfile("log.txt", ios::out|ios::app);
    dumpfile.write(statement.c_str(), statement.size());
}

void Logger::SetLevel(LEVEL level)
{
    assert(level >= LOG_DEBUG && level <= LOG_CRITICAL);
    level_ = level;
}

}
